package com.gongpingjialoan.activity.category;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.BuyCarVipActivity;
import com.gongpingjialoan.activity.car.NewUseCarAssResultActivity;
import com.gongpingjialoan.activity.loans.LoanIndexActivity;
import com.gongpingjialoan.activity.loans.MortgageLoanActivity;
import com.gongpingjialoan.activity.main.BaseFragment;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.main.ValueReportActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.activity.search.TopSearchActivity;
import com.gongpingjialoan.activity.tool.WebViewActivity;
import com.gongpingjialoan.adapter.LooperAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.BannerBean;
import com.gongpingjialoan.bean.BlogBean;
import com.gongpingjialoan.bean.BlogResult;
import com.gongpingjialoan.bean.Blogs;
import com.gongpingjialoan.bean.DataManager;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.AssPerfence;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.utility.GPSUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.DatePickerDialog;
import com.gongpingjialoan.view.DatePickerDialog.OnDialogCallBack;
import com.gongpingjialoan.view.GoodDealersView;
import com.gongpingjialoan.view.HotParamersView;
import com.gongpingjialoan.view.MainRecomendView;
import com.gongpingjialoan.view.MarqueeView;
import com.gongpingjialoan.view.ObservableScrollView;
import com.gongpingjialoan.view.ObservableScrollViewCallbacks;
import com.gongpingjialoan.view.ScrollState;
import com.gongpingjialoan.widget.MessageDialog;
import com.gongpingjialoan.widget.autoviewpagers.ColorPointHintView;
import com.gongpingjialoan.widget.autoviewpagers.RollPagerView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/***
 * 车辆估值 hqh
 *
 * @author Administrator
 */
public class AssessmentFragment extends BaseFragment implements OnClickListener, ObservableScrollViewCallbacks {

    private View view;

    private static final int REQUEST_MESSAGE = 0X091;

    private static final int REQUEST_LOAN = 0X195;

    public static final int REQUEST_BANNER_LOAN = 0X196;

    /**
     * 品牌
     */
    private String mBrandSlug;

    /**
     * 品牌名字
     */
    private String mBrandName;

    /**
     * 车型
     */
    private String mModelSlug;

    /**
     * 车型名称
     */
    private String mModelName;

    /**
     * 详细车型
     */
    private String mModelDetailSlug;

    /**
     * 详细车型名称
     */
    private String mModelDetailName;

    private String mModelThumbnail;

    private String mMile;

    private Button mBtnSure, sellButton;

    private TextView mTxtBrand;

    private TextView mTxtDate;

    private EditText mEdtMile;

    private LinearLayout rollmain_top;

    private String mYear;

    private String mMonth;

    private int mParallaxImageHeight;

    private MarqueeView mMarqueeView;
    /**
     * 日期选择弹框
     */
    private DatePickerDialog dateDialog;

    private TextView cityT;

    public HotParamersView mHotParamersView;

    public GoodDealersView gooddealers;

    private final int REQUEST_CITY_FRAGMENT = 1;

    private final int REQUEST_CITY_FRAGMENT1 = 10;

    private final int REQUEST_BRAND = 2;

    public static final int RESULT_EMPTY = 3;
    // 卖车页面跳转过来的时候使用,表示交易方式
    private int type = 0;

    private NetDataJson addHistoryNet, blogNetDataJson;
    private View imageLayout, searchView, searchBottom;
    public MainRecomendView mMainRecomendView;
    private View loc_layout;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private ImageView message_tip;
    private MessageDialog dialog;
    private TextView check_tv, loan_tv, car_loan_tv;
    private ImageView ass_image_top;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    String maxyear = null;

    String minyear = null;

    private boolean isHistory = false;

    private ObservableScrollView mScrollView;

    private TextView locTextView, locTextViewTop, mileTypeTextView;

    private RollPagerView mRollPagerView;

    private RollPagerView mRollPagerTopView;

    private LinearLayout rollLinearLayout;

    private RelativeLayout toolRelativeLayout;

    private LooperAdapter mLooperAdapter;

    private List<BannerBean.DataEntity.EvalEntity> dataEntities;

    private boolean isShowBanner = false;

    private String url = "", name = "";

    UserManager mUserManager;

    public BannerBean mBannerBean;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        action = "eval";
        isScrollPage = false;
        super.onCreate(savedInstanceState);
        registerBroadcastReceiver();
        mUserManager = new UserManager(getActivity());
        mUserManager = mUserManager.LoadUserInfo();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            stopPlay();
        } else {
            startPlay();
        }
    }

    public void stopPlay() {
        if (mRollPagerView != null) {
            mRollPagerView.stopPlay();
        }

        if (mRollPagerTopView != null) {
            mRollPagerTopView.stopPlay();
        }

    }

    public void startPlay() {
        if (mRollPagerView != null) {
            mRollPagerView.startPlay();
        }
        if (mRollPagerTopView != null) {
            mRollPagerTopView.startPlay();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.assessment_fragment, container,
                false);
        mParallaxImageHeight = DhUtil.dip2px(getActivity(), 130);
        gooddealers = (GoodDealersView) view.findViewById(R.id.gooddealers);
        mileTypeTextView = (TextView) view.findViewById(R.id.mile_type);
        mHotParamersView = (HotParamersView) view.findViewById(R.id.hot_view);
        imageLayout = view.findViewById(R.id.imagelayout);
        loc_layout = view.findViewById(R.id.loc_layout);
        searchView = view.findViewById(R.id.search);
        searchBottom = view.findViewById(R.id.search_bottom);
        mScrollView = (ObservableScrollView) view.findViewById(R.id.scrollview);
        mScrollView.setScrollViewCallbacks(this);
        locTextView = (TextView) view.findViewById(R.id.loc);
        locTextViewTop = (TextView) view.findViewById(R.id.loc_text);
        rollmain_top = (LinearLayout) view.findViewById(R.id.rollmain_top);

        locTextViewTop.setOnClickListener(this);
        rollLinearLayout = (LinearLayout) view.findViewById(R.id.rollmain);
        ass_image_top = (ImageView) view.findViewById(R.id.ass_image_top);
        mRollPagerView = new RollPagerView(getActivity());
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));
        mRollPagerView.setPlayDelay(3000);
        mRollPagerView.setVisibility(View.GONE);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.4f);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
        rollLinearLayout.addView(mRollPagerView, lp);

        mRollPagerTopView = new RollPagerView(getActivity());
        mRollPagerTopView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));
        mRollPagerTopView.setPlayDelay(3000);
        mRollPagerTopView.setVisibility(View.GONE);
        int width1 = getResources().getDisplayMetrics().widthPixels;
        int height1 = (int) (width * 0.46f);
        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(width1, height1);
        rollmain_top.addView(mRollPagerTopView, lp1);

        mMarqueeView = (MarqueeView) view.findViewById(R.id.marquee);
        message_tip = (ImageView) view.findViewById(R.id.message_tip);
        mMainRecomendView = (MainRecomendView) view.findViewById(R.id.mainrecomendView);
        sellButton = (Button) view.findViewById(R.id.sell_button);
//        mRollPagerView = (RollPagerView) view.findViewById(R.id.viewpager);
        toolRelativeLayout = (RelativeLayout) view.findViewById(R.id.toolbar);
        toolRelativeLayout.setBackgroundColor(Utils.getColorWithAlpha(0, getResources().getColor(R.color.new_color)));
        loc_layout.setAlpha(0f);
        searchView.setAlpha(0f);
        searchView.setOnClickListener(this);
        searchBottom.setOnClickListener(this);
        loc_layout.setOnClickListener(this);
        // EventBus.getDefault().register(getActivity());

        getNotification();

        mBtnSure = (Button) view.findViewById(R.id.eval_button);
        mTxtBrand = (TextView) view.findViewById(R.id.txt_model);
        mTxtDate = (TextView) view.findViewById(R.id.txt_year);
        mEdtMile = (EditText) view.findViewById(R.id.editText);
        cityT = (TextView) view.findViewById(R.id.txt_city);

        check_tv = (TextView) view.findViewById(R.id.check_tv);
        check_tv.setOnClickListener(this);
        loan_tv = (TextView) view.findViewById(R.id.loan_tv);
        loan_tv.setOnClickListener(this);
        car_loan_tv = (TextView) view.findViewById(R.id.car_loan_tv);
        car_loan_tv.setOnClickListener(this);

        initListener();
        cityT.setText(MainActivity.main.currentCity);

        locTextView.setText(MainActivity.main.currentCity);
        locTextViewTop.setText(MainActivity.main.currentCity);
//        view.findViewById(R.id.msg_img).setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                if (GPJApplication.getInstance().isLogin()) {
//                    //进入会话列表页面
//                    StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_chatNotification", System.currentTimeMillis(), 1.0f));
//                    startActivity(new Intent(getActivity(), MessageCenterActivity.class));
//                    message_tip.setVisibility(View.GONE);
//                } else {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), LoginActivity.class);
//                    startActivityForResult(intent, REQUEST_MESSAGE);
//                }
//
//            }
//        });

        // 城市选择
        cityT.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.putExtra("needProvince", false);
                intent.setClass(getActivity(), CityActivity.class);
                startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
            }
        });

        // 选择车型
        mTxtBrand.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!DataManager.getInstance().getLoadingDataSuccess()) {
                    Toast.makeText(getActivity(), "数据未加载成功,请检查网络是否连接!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getActivity(), CategoryActivity.class);
                intent.putExtra(Const.BRAND_NAME_KEY, mBrandName);
                intent.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
                intent.putExtra(Const.MODEL_NAME_KEY, mModelName);
                intent.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);
                intent.putExtra(Const.MODEL_DETAIL_NAME_KEY, mModelDetailName);
                intent.putExtra(Const.MODEL_DETAIL_SLUG_KEY, mModelDetailSlug);

                intent.putExtra("needModelDetailFragment", true);
                AssessmentFragment.this.startActivityForResult(intent, REQUEST_BRAND);

            }
        });

        // 选择上牌时间
        mTxtDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                        || mTxtBrand.getText().toString().equals("请选择您的爱车型号")) {
                    Toast.makeText(getActivity(), "请选择车辆型号!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (null != dateDialog && maxyear != null) {
                    dateDialog.show();
                } else {
                    Toast.makeText(getActivity(), "上牌时间数据加载中!",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        mBtnSure.setOnClickListener(this);
        sellButton.setOnClickListener(this);
        intAssHistory();
        getBolgs();



        mEdtMile.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mileTypeTextView.setText("万公里");
                } else {
                    if (!TextUtils.isEmpty(mEdtMile.getText().toString())) {
                        mileTypeTextView.setText("万公里");
                    } else {
                        mileTypeTextView.setText("行驶里程");
                    }
                }
            }
        });
        return view;
    }


    private void getBolgs() {
        if (blogNetDataJson == null) {
            blogNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    Gson gson = new Gson();
                    BlogResult blogResult = gson.fromJson(json, BlogResult.class);
                    if ("success".equals(blogResult.getStatus())) {
                        initBlog(blogResult);
                    }
                }
            }, 1);
        }
        blogNetDataJson.setUrl(API.blog);
        blogNetDataJson.request("get");
    }

    private void initBlog(BlogResult blogResult) {
        if (blogResult.getData().size() == 0) return;
        view.findViewById(R.id.blog_layout).setVisibility(View.VISIBLE);
        int size = blogResult.getData().size();

        List<Blogs> blogsList = new ArrayList<>();
        Blogs blogs;
        List<BlogBean> blogBeans = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if (blogBeans.size() == 2) {
                blogs = new Blogs();
                blogs.setChildren(blogBeans);
                blogsList.add(blogs);
                blogBeans = new ArrayList<>();
            }
            blogBeans.add(blogResult.getData().get(i));
            if (i == size - 1) {
                blogs = new Blogs();
                blogs.setChildren(blogBeans);
                blogsList.add(blogs);
            }
        }
        mMarqueeView.startWithList(blogsList);
        mMarqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(View textView) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_marketNews", System.currentTimeMillis(), 1f));
                StepMonitor.getInstance().addMonitor(new Monitor("enter", "eval_marketNews_detail", System.currentTimeMillis(), 1f));
                BlogBean blogBean = (BlogBean) textView.getTag();

                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", blogBean.getUrl());
                intent.putExtra("content", blogBean.getTitle());
                startActivity(intent);
            }
        });

    }


    public void intAssHistory() {
        AssPerfence assPerfence = AssPerfence.getInstance();
        assPerfence.load();
        if (TextUtils.isEmpty(assPerfence.getBrandName())) {
            return;
        }
        isHistory = true;
        mBrandSlug = assPerfence.getBrandSlug();
        mBrandName = assPerfence.getBrandName();
        mModelSlug = assPerfence.getModelSlug();
        mModelName = assPerfence.getModelName();
        mModelDetailName = assPerfence.getModelDetailName();
        mModelDetailSlug = assPerfence.getModelDetailSlug();
        mModelThumbnail = assPerfence.getModelThumbnail();

        if (mModelDetailName == null) {
            mTxtBrand.setText(mModelName);
        } else {
            mTxtBrand.setText(mModelName + " " + mModelDetailName);
        }
        // mTxtBrand.setTextColor(Color.parseColor("#666666"));

        mYear = assPerfence.getYear();
        mMonth = assPerfence.getMonth();
        if (TextUtils.isEmpty(mMonth)) {
            mTxtDate.setText(mYear + "年");
        } else {
            mTxtDate.setText(mYear + "年" + mMonth + "月");
        }
        // mTxtDate.setTextColor(Color.parseColor("#666666"));


        cityT.setText(assPerfence.getCity());
        double m = Double.parseDouble(assPerfence.getMile());
        if (m % 1 == 0) {
            mEdtMile.setText((int) m + "");
        } else {
            mEdtMile.setText(assPerfence.getMile());
        }
        mileTypeTextView.setText("万公里");

        dateDialog = new DatePickerDialog(getActivity());
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);
        dateDialog.setDialogCallBack(new OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    mTxtDate.setText(year + "年");
                } else {
                    mTxtDate.setText(year + "年" + month + "月");
                }
                //mTxtDate.setTextColor(Color.parseColor("#666666"));
            }


        });

        maxyear = assPerfence.getMaxyear();
        minyear = assPerfence.getMinyear();

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));


    }


    private void initAddHistory(AssessmentData assessmentData) {
        addHistoryNet = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                //刷新
            }
        });
        addHistoryNet.setUrl(API.addHistoryCars);
        addHistoryNet.addParam("brand", assessmentData.getBrandSlug());
        addHistoryNet.addParam("model", assessmentData.getModelSlug());
        addHistoryNet.addParam("model_detail", assessmentData.getModelDetailSlug());
        addHistoryNet.addParam("year", assessmentData.getYear());
        addHistoryNet.addParam("month", assessmentData.getMonth());
        addHistoryNet.addParam("mile", assessmentData.getMile());
        addHistoryNet.addParam("city", assessmentData.getCity());
        addHistoryNet.request("post");
    }

    public void changCity(String city) {
        if (!isHistory) {
            if (cityT != null) {
                cityT.setText(city);
            }
        }
        if (locTextView != null) {
            locTextView.setText(city);
        }
        if (locTextViewTop != null) {
            locTextViewTop.setText(city);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    if (!TextUtils.isEmpty(city)) {
                        cityT.setText(city);
                    }
                    break;
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT1:
                    String city1 = data.getExtras().getString("city");
                    if (!TextUtils.isEmpty(city1)) {
                        locTextView.setText(city1);
                        locTextViewTop.setText(city1);
                        GPJApplication.getInstance().getCityData().mCurrentCity = city1;
                        MainActivity.main.currentCity = city1;
                        Utils.changeCity(city1);
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user_city", Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString("city", city1);
                        edit.commit();
                        GPJApplication.getInstance().isChangeCity = true;
                        if (MainActivity.main != null) {
                            changCity(city1);
                            if (MainActivity.main.mRecomendDiscountFragment != null) {
                                MainActivity.main.mRecomendDiscountFragment.updateDiscountListData();
                            }
                            MainActivity.main.getNewCarActivity(city1);
                        }
                    }
                    break;
                // 车型选择回调
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    onBrandSelceted(bundle);
                    break;

                case REQUEST_MESSAGE:
//                    StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_chatNotification", System.currentTimeMillis(), 1.0f));
//                    startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                    break;
                case REQUEST_LOAN:
                    getOrderId();
                    break;
                case REQUEST_BANNER_LOAN:
                    mLooperAdapter.getOrderId();
                    break;
                default:
                    break;
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (addHistoryNet != null) {
            addHistoryNet.cancelTask();
            addHistoryNet = null;
        }
        if (blogNetDataJson != null) {
            blogNetDataJson.cancelTask();
            blogNetDataJson = null;
        }

        if (broadcastReceiver != null) {
            broadcastManager.unregisterReceiver(broadcastReceiver);
        }

        if (mMainRecomendView != null) {
            mMainRecomendView.canalTask();
        }
        if (gooddealers != null) {
            gooddealers.canalTask();
        }

    }

    // 选择完车型后,调用这辆
    public void onBrandSelceted(Bundle bundle) {
        maxyear = null;
        minyear = null;
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");
        mModelThumbnail = bundle.getString("modelThumbnail");

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            mTxtBrand.setText(mModelName);
        } else {
            mTxtBrand.setText(mModelName + " " + mModelDetailName);
        }
        //mTxtBrand.setTextColor(Color.parseColor("#666666"));

        // delete the date data if it is not null
        mTxtDate.setText("请选择");
        // mTxtDate.setTextColor(Color.parseColor("#18A0E0"));
        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(getActivity());
        dateDialog.setMinMonth(1);


        dateDialog.setMaxMonth(12);

        dateDialog.setDialogCallBack(new OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    mTxtDate.setText(year + "年");
                } else {
                    mTxtDate.setText(year + "年" + month + "月");
                }
                // mTxtDate.setTextColor(Color.parseColor("#666666"));
            }


        });

        // // 如果是评估我的车,上牌年份的日期从返回的数据bundle中取
        // if (radioG.getCheckedRadioButtonId() == R.id.radio_left)
        // {
        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(getActivity(), "没有可选的上牌时间!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mEdtMile.setText(null);

        if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                || mTxtBrand.getText().toString().equals("请选择您的爱车型号")) {
            Toast.makeText(getActivity(), "请选择车辆型号!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (null != dateDialog && maxyear != null) {
            dateDialog.show();
        } else {
            Toast.makeText(getActivity(), "上牌时间数据加载中!",
                    Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onClick(View v) {
        if (v == sellButton || v == mBtnSure) {
            if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                    || mTxtBrand.getText().toString().equals("请选择")) {
                Toast.makeText(getActivity(), "请选择车辆型号!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(mTxtDate.getText().toString()) || "请选择".equals(mTxtDate.getText().toString())) {
                Toast.makeText(getActivity(), "请选择上牌时间!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            mMile = mEdtMile.getText().toString();

            Double mile = -1.0;

            if (TextUtils.isEmpty(mMile)) {
                Toast.makeText(getActivity(), "请输入行驶里程!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (mMile.length() > 5) {
                Toast.makeText(getActivity(),
                        "请输入正确的公里数，小数和整数均不能超过2位数!", Toast.LENGTH_SHORT)
                        .show();
                return;
            }


            try {
                mile = Double.valueOf(mMile);
            } catch (NumberFormatException e) {
                Toast.makeText(getActivity(), "请填写正确的行驶里程（0-100万公里）",
                        Toast.LENGTH_SHORT).show();
                return;

            }

            if (mile < 0 || mile > 100) {
                Toast.makeText(getActivity(), "请填写正确的行驶里程（0-100万公里）",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            mMile = mile + "";

            // 将评估的数据存放起来,后面的页面用到的数据,基本都是从这边取的,除了CarListActivity(暂时是这样的)
            AssessmentData data = AssessmentData.getInstance();
            data.clear();
            data.setBrandName(mBrandName);
            data.setBrandSlug(mBrandSlug);
            data.setMile(mMile);
            data.setModelDetailName(mModelDetailName);
            data.setModelDetailSlug(mModelDetailSlug);
            data.setModelName(mModelName);
            data.setModelSlug(mModelSlug);
            data.setModelThumbnail(mModelThumbnail);
            data.setMonth(mMonth);
            data.setType(getType());
            data.setCity(cityT.getText().toString());
            data.setCar_id("");


            data.setYear(mYear);

            Intent it;
            String url;
            if (v == sellButton) {
                it = new Intent(getActivity(),
                        NewUseCarAssResultActivity.class);
                initAddHistory(data);
            } else {
                it = new Intent(getActivity(), ValueReportActivity.class);
                it.putExtra("isassessment", true);
                data.setStatus("");
                data.setCar_id("");
                String weburl = API.assessCarUrl
                        + data.getBrandSlug() + "/" + data.getModelSlug()
                        + "/" + data.getModelDetailSlug() + "/"
                        + data.getYear() + "-" + data.getMonth() + "/"
                        + data.getMile() + "/";


                it.putExtra("url", weburl);
                it.putExtra("isassessment", true);

                NetDataJson mNetDataJson = new NetDataJson(
                        new NetDataJson.OnNetDataJsonListener() {

                            @Override
                            public void onDataJsonUpdate(JSONObject json) {
                            }

                            @Override
                            public void onDataJsonError(
                                    String errorMessage) {
                            }
                        });

                mNetDataJson.setUrl(API.assessHistoryAdd);
                mNetDataJson.addParam("device_code", GPJApplication
                        .getInstance().getDeviceCode());
                mNetDataJson.addParam("brand", data.getBrandSlug());
                mNetDataJson.addParam("model", data.getModelSlug());
                mNetDataJson.addParam("model_detail",
                        data.getModelDetailSlug());
                mNetDataJson.addParam("year", data.getYear());
                mNetDataJson.addParam("month", data.getMonth());
                mNetDataJson.addParam("mile", data.getMile());
                mNetDataJson.addParam("city", data.getCity());
                mNetDataJson.addParam("condition", data.getStatus());
                mNetDataJson.addParam("pricetype", "");
                mNetDataJson.request("post");

            }
            getActivity().startActivity(it);

            AssPerfence per = AssPerfence.getInstance();
            per.setBrandName(mBrandName);
            per.setBrandSlug(mBrandSlug);
            per.setMile(mMile);
            per.setModelDetailName(mModelDetailName);
            per.setModelDetailSlug(mModelDetailSlug);
            per.setModelName(mModelName);
            per.setModelSlug(mModelSlug);
            per.setModelThumbnail(mModelThumbnail);
            per.setMonth(mMonth);
            per.setYear(mYear);
            per.setMaxyear(maxyear);
            per.setMinyear(minyear);
            per.setCity(cityT.getText().toString());
            per.commit();
            isHistory = true;
            if (MainActivity.main.sellCarFragment != null && MainActivity.main.sellCarFragment.isAdded()) {
                MainActivity.main.sellCarFragment.fromAssessData();
            }
        } else if (v == searchView || v == searchBottom) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_search", System.currentTimeMillis(), 1.0f));
            Intent intent = new Intent();
            intent.setClass(getActivity(), TopSearchActivity.class);
            startActivity(intent);
        } else if (v == rollmain_top) {
            if (!TextUtils.isEmpty(url)) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_mainActionBanner", System.currentTimeMillis(), 1.0f));
                if (TextUtils.isEmpty(name)) name = "公平价";
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("content", name);
                startActivity(intent);
            }
        } else if (v == loc_layout || v == locTextViewTop) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_cityChange", System.currentTimeMillis(), 1.0f));
            Intent cityit = new Intent();
            cityit.putExtra("needProvince", false);
            cityit.setClass(getActivity(), CityActivity.class);
            startActivityForResult(cityit, REQUEST_CITY_FRAGMENT1);
        } else if (v == check_tv) {
            Intent intent = new Intent(getActivity(), LoanIndexActivity.class);
            intent.putExtra("from", "home");
            startActivity(intent);
            /* String url = "";
           if (GPJApplication.getInstance().isLogin()) {
                mUserManager = mUserManager.LoadUserInfo();
                url = "http://m.gongpingjia.com/#hybrid_detectclue?phone=" + mUserManager.getPhone() + "&user_id=" + mUserManager.getUserid();
            } else {
                url = "http://m.gongpingjia.com/#hybrid_detectclue";
            }
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("url", url);
            intent.putExtra("content", "检测验车");
            startActivity(intent);*/
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_validationService", System.currentTimeMillis(), 1f));
        } else if (v == loan_tv) {
//            String city = Utils.getCityName(getActivity().getApplicationContext());
//            if (("苏州".equals(city) || "成都".equals(city))) {
//                if (GPJApplication.getInstance().isLogin()) {
//                    mLooperAdapter.getOrderId();
//
//                } else {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), LoginActivity.class);
//                    startActivityForResult(intent, REQUEST_BANNER_LOAN);
//                }
//
//            } else {
//                String url = "";
//                if (GPJApplication.getInstance().isLogin()) {
//                    mUserManager = mUserManager.LoadUserInfo();
//                    url = "http://m.gongpingjia.com/#loan?phone=" + mUserManager.getPhone() + "&user_id=" + mUserManager.getUserid();
//                } else {
//                    url = "http://m.gongpingjia.com/#loan";
//                }
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                intent.putExtra("url", url);
//                intent.putExtra("content", "买车贷款");
//                startActivity(intent);
//            }
            mUserManager = mUserManager.LoadUserInfo();
//            if (GPJApplication.getInstance().isLogin()) {
            Intent intent = new Intent(getActivity(), BuyCarVipActivity.class);
            intent.putExtra("from","carlist");
            startActivity(intent);

//            } else {
//                Intent intent = new Intent(getActivity(), VIPDetailActivity.class);
//                startActivity(intent);
//                StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_loanService", System.currentTimeMillis(), 1f));
//            }

        } else if (v == car_loan_tv) {
//            String city = Utils.getCityName(getActivity().getApplicationContext());
//            if (("苏州".equals(city) || "成都".equals(city))) {
//                if (GPJApplication.getInstance().isLogin()) {
//                    getOrderId();
//                } else {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), LoginActivity.class);
//                    startActivityForResult(intent, REQUEST_LOAN);
//                }
//
//            } else {
//                String url = "";
//                if (GPJApplication.getInstance().isLogin()) {
//                    mUserManager = mUserManager.LoadUserInfo();
//                    url = "http://m.gongpingjia.com/#hybrid_mortgageloan?phone=" + mUserManager.getPhone() + "&user_id=" + mUserManager.getUserid();
//                } else {
//                    url = "http://m.gongpingjia.com/#hybrid_mortgageloan";
//                }
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                intent.putExtra("url", url);
//                intent.putExtra("content", "车抵贷");
//                startActivity(intent);
//            }
            if (GPJApplication.getInstance().isLogin()) {
                getOrderId();
            } else {
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                startActivityForResult(intent, REQUEST_LOAN);
            }
            StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_carMortgageLoan", System.currentTimeMillis(), 1f));
        }
    }


    public void setBanerImage(BannerBean bannerBean) {
//        BannerBean bannerBean = GPJApplication.getInstance().mBannerBean;
        if (!isShowBanner && bannerBean != null && "success".equals(bannerBean.getStatus())) {
            isShowBanner = true;
            List<BannerBean.DataEntity.EvalEntity> topImages = bannerBean.getData().getMainactivity();

            dataEntities = bannerBean.getData().getEval();
            Log.d("msg1", "dataEntities:" + dataEntities.toString());
            if (dataEntities != null && dataEntities.size() > 0) {
                mRollPagerView.setVisibility(View.VISIBLE);
                mLooperAdapter = new LooperAdapter(mRollPagerView, dataEntities, getActivity(), getFragmentManager(), true);
                mRollPagerView.setAdapter(mLooperAdapter);
            }
            Log.d("msg1", "topImages:" + topImages.toString());
            if (topImages != null && topImages.size() > 0) {
                ass_image_top.setVisibility(View.GONE);
                mRollPagerTopView.setVisibility(View.VISIBLE);
                LooperAdapter mLooperAdapter1 = new LooperAdapter(mRollPagerTopView, topImages, getActivity(), getFragmentManager(), true, true);
                mRollPagerTopView.setAdapter(mLooperAdapter1);
            }
        }
    }

    private void registerBroadcastReceiver() {
//        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
//        broadcastReceiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                if (intent.getIntExtra("ack", 0) == 1) {
//                    message_tip.setVisibility(View.GONE);
//                } else {
//                    message_tip.setVisibility(View.VISIBLE);
//                }
//            }
//
//        };
//        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }


    private int scrollY = 0;

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        this.scrollY = scrollY;
        int baseColor = getResources().getColor(R.color.new_color);
        float alpha = Math.min(1, (float) scrollY / mParallaxImageHeight);
        toolRelativeLayout.setBackgroundColor(Utils.getColorWithAlpha(alpha, baseColor));
        if (alpha > 0.15f) {
            toolRelativeLayout.setVisibility(View.VISIBLE);
        } else {
            toolRelativeLayout.setVisibility(View.GONE);
        }
        loc_layout.setAlpha(alpha);
        searchView.setAlpha(alpha);
        imageLayout.setTranslationY(scrollY / 2);
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        if (scrollY < mParallaxImageHeight * 0.65f) {
            mScrollView.post(new Runnable() {
                @Override
                public void run() {
                    mScrollView.fullScroll(ScrollView.FOCUS_UP);
                }
            });
        } else if (scrollY >= mParallaxImageHeight * 0.65f && scrollY <= mParallaxImageHeight) {
            mScrollView.post(new Runnable() {
                @Override
                public void run() {
                    mScrollView.smoothScrollTo(0, mParallaxImageHeight);
                }
            });
        }
        //
    }

    public void setRecomendVis() {
        mMainRecomendView.setVisibility(View.VISIBLE);
    }


    private void initListener() {
        mTxtBrand.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mTxtBrand.getText().toString()) || "请选择您的爱车型号".equals(mTxtBrand.getText().toString())) {
                    mTxtBrand.setTextColor(Color.parseColor("#999999"));
                } else {
                    mTxtBrand.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        mTxtDate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mTxtDate.getText().toString()) || "上牌时间".equals(mTxtDate.getText().toString()) || "请选择".equals(mTxtDate.getText().toString())) {
                    mTxtDate.setTextColor(Color.parseColor("#999999"));
                } else {
                    mTxtDate.setTextColor(Color.parseColor("#333333"));
                }
            }
        });


        mEdtMile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mEdtMile.getText().toString())) {
                    mEdtMile.setTextColor(Color.parseColor("#999999"));
                    mileTypeTextView.setTextColor(Color.parseColor("#999999"));
                } else {
                    mEdtMile.setTextColor(Color.parseColor("#333333"));
                    mileTypeTextView.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        cityT.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(cityT.getText().toString()) || "上牌城市".equals(cityT.getText().toString())) {
                    cityT.setTextColor(Color.parseColor("#999999"));
                } else {
                    cityT.setTextColor(Color.parseColor("#333333"));
                }
            }
        });
    }


    public void getNotification() {
        NetDataJson netNetDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {

            }

            @Override
            public void onDataJsonUpdate(String json) {
                Gson gson = new Gson();
                mBannerBean = gson.fromJson(json, BannerBean.class);
                GPJApplication.getInstance().mBannerBean = mBannerBean;
                if ("success".equals(mBannerBean.getStatus())) {
                    EventBus.getDefault().post("notification");
                    setBanerImage(mBannerBean);
                }
            }
        }, 1);
        netNetDataJson.setUrl(API.getBanner);
        netNetDataJson.request("get");
    }

    private void getOrderId() {
        Intent it = new Intent(getActivity(),MortgageLoanActivity.class);
        startActivity(it);
//        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
//            @Override
//            public void onDataJsonError(String errorMessage) {
//                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onDataJsonUpdate(String json) {
//                Gson gson = new Gson();
//                LoanOrderData loanOrderData = gson.fromJson(json, LoanOrderData.class);
//                String order_id = loanOrderData.getData().getOrder_no();
//                String user_id = loanOrderData.getData().getUser_id();
//                gotoWeb(order_id, user_id);
//            }
//        }, 1);
//        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.loan_get_order_id);
//        netDataJson.setUseOtherDomain(true);
//        netDataJson.addParam("source", 3);
//        netDataJson.request("post");

    }

    public void loginforBannerLoan() {
        Intent i = new Intent();
        i.setClass(getActivity(), LoginActivity.class);
        startActivityForResult(i, AssessmentFragment.REQUEST_BANNER_LOAN);
    }

    private void gotoWeb(String order_id, String user_id) {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "eval_flashloan_mortage", System.currentTimeMillis(), 1f));

        Intent intent = new Intent(getActivity(), WebViewActivity.class);
        String url = "http://www.eflashloan.com/eflashadv/index.html#" + order_id;
        intent.putExtra("url", url);

        intent.putExtra("type", "eval_flashloan_mortage");
        intent.putExtra("order_id", order_id);
        intent.putExtra("user_id", user_id);
        intent.putExtra("vehicle_value", "");
        intent.putExtra("access_ip", GPSUtil.getLocalIpAddress());
        intent.putExtra("source", 3);
        intent.putExtra("loadType", "post");
        intent.putExtra("url", url);
        intent.putExtra("content", "车抵贷");
        intent.putExtra("city", Utils.getCityName(getActivity().getApplicationContext()));
        startActivity(intent);

    }
}
